#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include "video.h"
#include "png.h"

extern int *lcd_ptr;

// 全局变量
static VideoFile *video_files = NULL;
static int video_count = 0;
static int current_video = 0;
static int current_page = 0;
static int video_per_page = 6;
static pid_t mplayer_pid = -1;
static VideoState video_state = VIDEO_STOPPED;
static char current_playing[512] = "";
static int is_fullscreen = 0;
static int av_fd = -1; // 与mplayer通信的管道文件描述符

// 清屏函数
static void clear_screen(int color) {
    for (int i = 0; i < 800 * 480; i++) {
        lcd_ptr[i] = color;
    }
}

// 绘制视频背景
static void draw_video_bg(int x, int y, int width, int height) {
    for (int py = y; py < y + height; py++) {
        for (int px = x; px < x + width; px++) {
            if (px >= 0 && px < 800 && py >= 0 && py < 480) {
                lcd_ptr[py * 800 + px] = 0x808080; // 灰色背景
            }
        }
    }
}

// 绘制播放状态边框
static void draw_playing_border(int x, int y, int width, int height) {
    for (int py = y - 2; py < y + height + 2; py++) {
        for (int px = x - 2; px < x + width + 2; px++) {
            if (px >= 0 && px < 800 && py >= 0 && py < 480) {
                if (py == y - 2 || py == y + height + 1 || px == x - 2 || px == x + width + 1) {
                    lcd_ptr[py * 800 + px] = 0x00FF00;
                }
            }
        }
    }
}

// 绘制底部播放栏
static void draw_playbar(void) {
    // 绘制白色底部播放栏
    for (int y = 400; y < 480; y++) {
        for (int x = 0; x < 800; x++) {
            lcd_ptr[y * 800 + x] = 0xFFFFFF; // 白色播放栏
        }
    }
}

// 发送命令到mplayer
static void send_cmd(const char *cmd) {
    if (av_fd > 0) {
        write(av_fd, cmd, strlen(cmd));
    }
}

// 获取文件名（不含扩展名）
static char* get_filename_without_ext(const char *filename) {
    static char name[256];
    strcpy(name, filename);
    char *dot = strrchr(name, '.');
    if (dot) *dot = '\0';
    return name;
}

// 绘制控制按钮图片
static void draw_control_buttons(void) {
    int button_start_x = 260;
    int button_y = 400;
    
    lcd_draw_scale_png("/zdata/icon/rewind.png", button_start_x, button_y, 80, 80);
    
    // 根据播放状态显示不同的按钮
    if (video_state == VIDEO_PLAYING) {
        lcd_draw_scale_png("/zdata/icon/pause.png", button_start_x + 100, button_y, 80, 80);
    } else {
        lcd_draw_scale_png("/zdata/icon/play.png", button_start_x + 100, button_y, 80, 80);
    }
    
    lcd_draw_scale_png("/zdata/icon/fast_forward.png", button_start_x + 200, button_y, 80, 80);
}

// 加载视频封面
static int load_video_covers(VideoFile *files, int count) {
    for (int i = 0; i < count; i++) {
        char *name_without_ext = get_filename_without_ext(files[i].name);
        snprintf(files[i].cover_path, sizeof(files[i].cover_path), "/zdata/cover/%s.png", name_without_ext);
        
        struct stat st;
        files[i].has_cover = (stat(files[i].cover_path, &st) == 0);
    }
    return 0;
}

// 显示视频封面
static int display_video_cover(const char *cover_path, int x, int y, int width, int height) {
    return cover_path ? lcd_draw_scale_png(cover_path, x, y, width, height) : -1;
}

// 获取视频文件列表
int get_video_files(VideoFile *files, int max_files) {
    DIR *dir = opendir("/zdata/video");
    if (!dir) return 0;
    
    struct dirent *entry;
    int count = 0;
    
    while ((entry = readdir(dir)) != NULL && count < max_files) {
        char *name = entry->d_name;
        char *ext = strrchr(name, '.');
        
        if (ext) {
            char lower_ext[10];
            strcpy(lower_ext, ext);
            for (int i = 0; lower_ext[i]; i++) {
                lower_ext[i] = tolower(lower_ext[i]);
            }
            
            if (strcmp(lower_ext, ".mp4") == 0 || 
                strcmp(lower_ext, ".avi") == 0 || 
                strcmp(lower_ext, ".mkv") == 0 ||
                strcmp(lower_ext, ".mov") == 0 ||
                strcmp(lower_ext, ".wmv") == 0 ||
                strcmp(lower_ext, ".flv") == 0) {
                
                snprintf(files[count].path, sizeof(files[count].path), "/zdata/video/%s", name);
                strcpy(files[count].name, name);
                files[count].duration = 0;
                files[count].width = 0;
                files[count].height = 0;
                files[count].has_cover = 0;
                count++;
            }
        }
    }
    
    closedir(dir);
    if (count > 0) load_video_covers(files, count);
    return count;
}

// 播放视频文件
int play_video(const char *file_path) {
    if (mplayer_pid > 0) {
        kill(mplayer_pid, SIGTERM);
        waitpid(mplayer_pid, NULL, 0);
        mplayer_pid = -1;
        if (av_fd > 0) {
            close(av_fd);
            av_fd = -1;
        }
    }
    
    unlink("/tmp/mplayer_control");
    if (mkfifo("/tmp/mplayer_control", 0666) == -1) return -1;
    
    mplayer_pid = fork();
    if (mplayer_pid == 0) {
        execlp("mplayer", "mplayer", "-vo", "fbdev2", "-zoom", "-x", "800", "-y", "400", 
               "-quiet", "-framedrop", "-input", "file=/tmp/mplayer_control", file_path, NULL);
        exit(1);
    } else if (mplayer_pid > 0) {
        av_fd = open("/tmp/mplayer_control", O_WRONLY);
        if (av_fd == -1) return -1;
        
        video_state = VIDEO_PLAYING;
        strcpy(current_playing, file_path);
        is_fullscreen = 1;
        
        usleep(500000);
        draw_control_buttons();
        return 0;
    }
    return -1;
}

// 全屏播放视频
int play_video_fullscreen(const char *file_path) {
    return play_video(file_path);
}

// 停止视频播放
int stop_video(void) {
    if (mplayer_pid > 0) {
        kill(mplayer_pid, SIGTERM);
        waitpid(mplayer_pid, NULL, 0);
        mplayer_pid = -1;
        if (av_fd > 0) {
            close(av_fd);
            av_fd = -1;
        }
    }
    video_state = VIDEO_STOPPED;
    current_playing[0] = '\0';
    is_fullscreen = 0;
    
    // 如果不在全屏模式，刷新UI显示
    if (!is_fullscreen) {
        show_video_ui();
    }
    return 0;
}

// 暂停/恢复视频播放
int pause_resume_video(void) {
    if (mplayer_pid > 0) {
        if (video_state == VIDEO_PLAYING) {
            send_cmd("pause\n");
            video_state = VIDEO_PAUSED;
        } else if (video_state == VIDEO_PAUSED) {
            send_cmd("pause\n");
            video_state = VIDEO_PLAYING;
        }
        
        // 刷新控制按钮显示
        if (is_fullscreen) {
            draw_control_buttons();
        }
    }
    return 0;
}

// 快进10秒
int fast_forward_video(void) {
    if (mplayer_pid > 0 && video_state == VIDEO_PLAYING) {
        send_cmd("seek 10\n");
    }
    return 0;
}

// 快退10秒
int rewind_video(void) {
    if (mplayer_pid > 0 && video_state == VIDEO_PLAYING) {
        send_cmd("seek -10\n");
    }
    return 0;
}

// 获取当前播放状态
VideoState get_video_state(void) {
    if (mplayer_pid > 0) {
        int status;
        if (waitpid(mplayer_pid, &status, WNOHANG) > 0) {
            mplayer_pid = -1;
            if (av_fd > 0) {
                close(av_fd);
                av_fd = -1;
            }
            video_state = VIDEO_STOPPED;
            current_playing[0] = '\0';
            is_fullscreen = 0;
        }
    }
    return video_state;
}

// 显示影音播放器界面
int show_video_ui(void) {
    if (is_fullscreen) return 0;
    
    if (!video_files) {
        video_files = calloc(512, sizeof(VideoFile));
        video_count = get_video_files(video_files, 512);
    }
    
    clear_screen(0x808080); // 灰色背景
    draw_playbar(); // 绘制白色播放栏
    
    int start_idx = current_page * video_per_page;
    int end_idx = start_idx + video_per_page;
    if (end_idx > video_count) end_idx = video_count;
    
    // 显示视频列表
    for (int i = start_idx; i < end_idx; i++) {
        int row = (i - start_idx) / 3;
        int col = (i - start_idx) % 3;
        int x = 50 + col * 250;
        int y = 50 + row * 200;
        
        // 显示封面或默认背景
        if (video_files[i].has_cover) {
            display_video_cover(video_files[i].cover_path, x, y, 180, 120);
        } else {
            draw_video_bg(x, y, 180, 120);
        }
        
        // 绘制播放状态指示器
        if (strcmp(video_files[i].path, current_playing) == 0) {
            draw_playing_border(x, y, 180, 120);
        }
    }
    
    draw_control_buttons();
    return 0;
}

// 处理控制按钮触摸
static int handle_control_buttons(int x, int y) {
    int button_start_x = 260;
    int button_y = 400;
    
    // 快退按钮
    if (x >= button_start_x && x < button_start_x + 80 && y >= button_y && y < button_y + 80) {
        rewind_video();
        return 1;
    }
    
    // 暂停/播放按钮
    if (x >= button_start_x + 100 && x < button_start_x + 180 && y >= button_y && y < button_y + 80) {
        if (get_video_state() == VIDEO_PLAYING) {
            pause_resume_video();
        } else if (get_video_state() == VIDEO_PAUSED) {
            pause_resume_video();
        } else if (video_count > 0) {
            play_video_fullscreen(video_files[current_video].path);
        }
        return 1;
    }
    
    // 快进按钮
    if (x >= button_start_x + 200 && x < button_start_x + 280 && y >= button_y && y < button_y + 80) {
        fast_forward_video();
        return 1;
    }
    
    return 0;
}

// 处理影音播放器触摸事件
int handle_video_touch(int x, int y) {
    // 全屏模式控制
    if (is_fullscreen) {
        if (x < 100 && y < 100 && video_count > 0) {
            stop_video();
            current_video = (current_video - 1 + video_count) % video_count;
            play_video_fullscreen(video_files[current_video].path);
            return 1;
        }
        if (x > 700 && y < 100 && video_count > 0) {
            stop_video();
            current_video = (current_video + 1) % video_count;
            play_video_fullscreen(video_files[current_video].path);
            return 1;
        }
        if (x > 700 && y > 300) {
            stop_video();
            show_video_ui();
            return 1;
        }
        return handle_control_buttons(x, y);
    }
    
    // 翻页按钮
    if (y < 100) {
        if (x < 100 && current_page > 0) {
            current_page--;
            show_video_ui();
            return 1;
        }
        if (x > 700) {
            int max_page = (video_count + video_per_page - 1) / video_per_page;
            if (current_page < max_page - 1) {
                current_page++;
                show_video_ui();
                return 1;
            }
        }
    }
    
    // 视频选择区域
    int start_idx = current_page * video_per_page;
    for (int i = 0; i < video_per_page; i++) {
        int row = i / 3;
        int col = i % 3;
        int video_x = 50 + col * 250;
        int video_y = 50 + row * 200;
        
        if (x >= video_x && x < video_x + 180 && y >= video_y && y < video_y + 120) {
            int video_idx = start_idx + i;
            if (video_idx < video_count) {
                current_video = video_idx;
                play_video_fullscreen(video_files[video_idx].path);
            }
            return 1;
        }
    }
    
    // 播放控制区域
    if (y > 400) {
        return handle_control_buttons(x, y);
    }
    
    return 0;
} 